/* Helper functions */

loader_txt = '';

function loader( t ) {
  
  $ = jQuery;
  
  if( t === 'show' ) {
  	
  	$( '.loader' )
  	  .stop( true, true )
  	  .show();
  	if( loader_txt != '' ) {
  		
  		$( '.loader' ).css( { padding: '71px 3px 10px 3px', width: 71, height: 'auto'  } )
  		
  		$( '<p></p>' )
  		  .appendTo( '.loader' )
  		  .text( loader_txt );
  		
  	}
  	
  } else {
  	
  	$( '.loader' )
  	  .stop( true, true )
  	  .fadeOut(300, function(){
  	  	
  	  	$(this)
  	  	  .css( { padding: 0, width: 77, height: 77 } )
  	  	  .children('p')
  	      .remove();
  	  	
  	  } )
  	
  }
  
}

function message( type, message ) {
  
  $ = jQuery;
  
  if( type == 'warning' ) { 
    
    type = 'bar_red';
    
  } else if( type == 'info' ) { 
    
    type = 'bar_blue';
    
  } else {
    
    type = ''
    
  }
  
  $( '<div class="bar bar_will_disappear '+type+'"/>' ).appendTo('.container').text(message).click( hide_message );
  
  reset_message_hide_timeout();
  
}

function hide_message() {
  
  $ = jQuery;
  
  if( window.message_hide_timeout !== undefined )
    clearTimeout( message_hide_timeout );
  
  $( '.bar_will_disappear:last' ).fadeOut(300, function(){
    
    $(this).remove();
    
  });
  
  set_message_hide_timeout();
  
}

function reset_message_hide_timeout() {
  
  $ = jQuery;
  
  if( window.message_hide_timeout !== undefined )
    clearTimeout( message_hide_timeout );
  
  set_message_hide_timeout();
  
}

function set_message_hide_timeout() {
  
  $ = jQuery;
  
  t = $( '.bar_will_disappear:last' ).text().length * 68; //base timeout on amount of characters
  message_hide_timeout = setTimeout( 'hide_message()', ( t < 5000 ? 5000 : t ) );
  
}

/*  The "guts" :) */

//some 'global' vars
curr_mode = '';
ajax = false;

function new_word( mode ) {
  
  $ = jQuery;
  
  if( ajax !== false )
    ajax.abort();
  
  ajax = $.ajax(i18n.ajaxurl, {
    
    async: false,
    type: 'POST',
    data: 'action=get_random_word',
    success: function( data ){
      
      if( $.isEmptyObject( data ) ) {
        
        message( 'warning', i18n.no_words_found );
        
      } else {
        
        setup_word_guess( mode, data.words, data.images_src );
        curr_mode = mode;
        
      }
      
      ajax = false;
      
    }
    
  });
  
}

function setup_word_guess( mode, words, images ) {
  
  $ = jQuery;
  
  $.loadImages(images, function(){ 
    
    images_html = '';
    $.each( images, function(i,val){
      
      images_html += '<div><img src="'+val+'" alt="" class="guess_image" /></div>';
      
    });
    
    $( '.guessing_game,.status,.nav' ).remove();
	  
	  
	  $( '.container' )
	    .prepend( '<div class="nav">| <a href="javascript:new_word( \'' +curr_mode+ '\' )">new word</a> | <a href="javascript:setup_main_page()">back to menu</a></div>' )
	    .append( '<div class="content" />' );
	  
	  keys_to_bind = []
	  
	  $.each( words, function(i,val){
	  	
	  	word_split = val.split('');
	    words_html = '';
	    $.each(word_split, function(i,val) {
	    	
	    	words_html += '<span rel="' +val+ '"' +( i == 0 ? ' class="to_guess"' : '' )+ '>'
	    	  +( mode === 'learn' ? val : '.' )+'</span>';
	      
	    } );
	    $( '.container' ).append('<div class="guessing_game banner">'+words_html+'</div>');
	    
	    if( $.inArray( word_split[0], keys_to_bind ) === -1 ) { keys_to_bind.push( word_split[0] ); }
	  
	  });
	  
	  $( '.container' ).append( '<div class="status" />' );
	  
	  $('.guessing_game').show().not(':first').hide();
	  
	  $( '.content:last' )
	    .append('<div class="post_content">'+images_html+'</div>')
	    .hide().slideToggle();
        
    $( '.header h1' ).text( i18n.learn );
		$('.status').text( ( mode === 'learn' ? i18n.status_learn : i18n.status_study ) );
	  
	  $( '.post_content' ).cycle();
	  
	  $( '.content:first' ).slideToggle( function() { $(this).remove(); } );
	  
	  $.each(keys_to_bind, function(i,val){
	    
	  	bind_key( val );
	  	
	  })
	  
  })
  
}

function bind_key( key ) {
	
	$ = jQuery;
	
	shortcut.add( key, function() {
		
		shortcut.removeAll();
		
		to_bind = [];
		
		$( '.to_guess' )
		  .removeClass( 'to_guess' )
		  .addClass( 'guessed' )
		  .each(function() {
				
				$(this).text( $(this).attr( 'rel' ) );
				
				if( $(this).attr( 'rel' ) != key ) {
					
					$(this).parent().remove();
					$('.guessing_game').show().not(':first').hide();
					return;
					
				}
				
				if( $('.guessed').length !== $('.guessed').next().length ) {
					
					//well, you passed the test. i forgot how good you are at this.
					$( '.guessing_game' ).addClass('guessed');
					$('.status').text( i18n.well_done );
					
					setTimeout( function() { new_word( curr_mode ); }, 3000 );
					
				} else {
					
					$(this).next().addClass( 'to_guess' );
					to_bind.push( $(this).next().attr( 'rel' ) );
					
				}
				
			} );
		
		keys_to_bind = []
		
		$.each( to_bind, function(i,val){
			
			if( $.inArray( val, keys_to_bind ) === -1 ) {
				
				keys_to_bind.push( val );

			}
			
		} );
		
		$.each( keys_to_bind, function(i,val){
			
			bind_key( val );
	  
		} );
			  	
	} );
	
}

function setup_main_page() {
  
  $ = jQuery;
  
  /* Setup the main page */
 
  $( '.guessing_game,.status,.nav' ).remove();
  
  $( '.header h1' ).text( i18n.welcome );
	  
  $( '.container' ).append( '<div class="content" />' );
  $( '.content:last' )
    .append('<div class="game_modes"></div>')
    .hide().slideDown();
  
  $('.content:first').slideUp( function() { $(this).remove(); } );
  
  $( '.game_modes' )
    .empty()
    .append( '<h2 class="aligncenter">'+i18n.what_do_you_want_to_do+'</h2>' )
    .append( '<div class="col1" />' ).append( '<div class="col2" />' )//.append( '<div class="col3" />' )
    .append( '<div class="clearboth" />' );
  
  $( '.game_modes .col1' ).append( '<h3><a href="#">'+i18n.learn+'</a></h3>' )
    .find( 'h3' ).click(function(e){
      e.preventDefault();
      new_word( 'learn' );
    });
  
  $( '.game_modes .col2' ).append( '<h3><a href="#">'+i18n.study+'</a></h3>' )
    .find( 'h3' ).click(function(e){
      e.preventDefault();
      new_word( 'study' );
    });
  
  //coming soon!
  // $( '.game_modes .col3' ).append( '<h3><a href="#">'+i18n.test+'</a></h3>' )
    // .find( 'h3' ).click(function(e){
      // e.preventDefault();
      // start_test();
    // });
  
}

jQuery(document).ready(function($){

  $(document).ajaxStart(function(){
    
    loader( 'show' );
    
  }).ajaxStop(function(){
    
    loader( 'hide' );
    
  }).ajaxError(function(){
    
    message('warning', i18n.ajax_error)
    
  });
  
  set_message_hide_timeout();
	
	setup_main_page();
	
	/* graphical fixes */
	$( '.container:has(".bar")' ).css( { paddingBottom: 45 } );
  
});